package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Enum.ResultStatus;
import com.example.demo.VO.PaperDetailedVO;
import com.example.demo.VO.PaperVO;
import com.example.demo.VO.Result;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import com.example.demo.util.RedisUtils;
import com.sun.istack.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (Paper)表控制层
 *
 * @author hjl
 * @since 2020-12-01 10:27:01
 */
@Api(value = "试卷", tags = {"试卷操作接口"})
@RestController
@RequestMapping("paper")
public class PaperController {
    /**
     * 服务对象
     */
    @Resource
    private PaperService paperService;

    @Resource
    private ChoiceService choiceService;

    @Resource
    private JudgmentService judgmentService;

    @Resource
    private BlankService blankService;

    @Resource
    private Short1Service short1Service;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private PaperHistoryService paperHistoryService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */

    @GetMapping("selectOne")
    public Paper selectOne(Integer id) {
        return this.paperService.queryById(id);
    }

    @ApiOperation(value = "添加试卷", tags = {"用户id、题目类型、题目id"}, notes = "不用注意问题")
    @PostMapping("addPaper")
    public Result addPaper(@RequestBody Paper paper) {
        return Result.success(paperService.insert(paper));
    }

    @ApiOperation(value = "获取试卷", tags = {"试卷的id"}, notes = "暂时不用注意问题")
    @GetMapping("getPaper")
    public Result getPaper(Integer paperId) {
        Paper paper = new Paper();
        paper = paperService.queryById(paperId);
        paper.setId(paperId);
        if (paper == null) {
            return Result.failure("未找到试卷");
        }
        return Result.success(paper);
    }

    @ApiOperation(value = "删除试卷", tags = {"试卷id"}, notes = "啦啦啦啦啦啦")
    @DeleteMapping("delPaper")
    public Result delPaper(Integer paperId) {
        Boolean a = paperService.deleteById(paperId);
        if (a) {
            return Result.failure("删除失败咯");
        }

        return Result.success("删除成功");
    }

    @ApiOperation(value = "更新试卷", tags = {"试卷实体类数据"}, notes = "注意问题点")
    @PostMapping("updatePaper")
    public Result updatePaper(Paper paper) {
        return Result.success(paperService.update(paper));
    }

    @ApiOperation(value = "获取某个老师的所有试卷", tags = {"老师的id"}, notes = "注意问题点")
    @GetMapping("getUserPaper")
    public Result getUserPaper(Integer userId) {
        Paper paper = new Paper();
        List<Paper> paperList = new ArrayList<Paper>();
        paper.setUserId(userId);
        paperList = paperService.queryByExample(paper);
        Map<Integer, String> paperMap = new HashMap<>();
        for (Paper s : paperList) {
            paperMap.put(s.getId(), s.getObj1());
        }
        if (paperList.size() == 0) {
            return Result.failure("未找到试卷");
        }
        return Result.success(paperMap);
    }

    @ApiOperation(value = "获取某个课程的所有试卷", tags = {"课程的id"}, notes = "注意问题点")
    @GetMapping("getCoursePaper")
    public Result getCoursePaper(int CourseId) {

        Paper paper = new Paper();
        List<Paper> paperList = new ArrayList<Paper>();
        paper.setObj2(CourseId + "");
        paperList = paperService.queryByExample(paper);
        List<PaperVO> list = new ArrayList<>();
        for (Paper s : paperList) {
            list.add(new PaperVO(s.getId(), s.getObj1(), s.getCreatetime(), s.getUpdatetime()));
        }
        if (paperList.size() == 0) {
            return Result.failure("未找到试卷");
        }
        return Result.success(list);
    }

    @ApiOperation(value = "获取试卷详情", tags = {"试卷的id"}, notes = "注意问题点")
    @GetMapping("getPaperDetailed")
    public Result getPaperDetailed(int paperId,int userId) {
        String o= String.valueOf(redisUtils.get("paperUser:"+userId));
        JSONObject paperH=JSON.parseObject(o);
        PaperHistory paperHistory=new PaperHistory();
        if (paperH==null){
            System.out.println("数据不存在");
            PaperHistory paperHistory1=new PaperHistory();
            paperHistory1.setPaperId(paperId);
            paperHistory1.setUserId(userId);
            paperHistory=paperHistoryService.insert(paperHistory1);
        }else{
            System.out.println("数据已存在");
            String id= String.valueOf(paperH.get("historyId"));
            paperHistory=paperHistoryService.queryById(Integer.valueOf(id));
        }
        Paper paper = paperService.queryById(paperId);
        String[] questionIds = paper.getQuestionId().split(",");
        String[] questionTypes = paper.getQuestionType().split(",");
        List<Object> PaperDetailed = new ArrayList<>();
        for (int i = 0; i < questionIds.length; i++) {
            if (questionTypes[i].equals("0")) {
                Choice choice = choiceService.queryById(Integer.valueOf(questionIds[i]));
                PaperDetailed.add(choice);
            } else if (questionTypes[i].equals("1")) {
                Judgment judgment = judgmentService.queryById(Integer.valueOf(questionIds[i]));
                PaperDetailed.add(judgment);
            } else if (questionTypes[i].equals("2")) {
                Blank blank = blankService.queryById(Integer.valueOf(questionIds[i]));
                PaperDetailed.add(blank);
            } else {
                Short1 short1 = short1Service.queryById(Integer.valueOf(questionIds[i]));
                PaperDetailed.add(short1);
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("paper",new PaperDetailedVO(paperId, questionTypes, PaperDetailed));
        map.put("o",o);
        map.put("paperHistory",paperHistory.getId());
        return Result.success(map);
    }

    @PostMapping("temporarilyPaper")
    public ResponseEntity<Map> temporarilyPaper (@RequestBody Map<String,String> Data){
        redisUtils.set("paperUser:"+Data.get("userId"),JSON.toJSONString(Data),new Long(90), TimeUnit.MINUTES);
        PaperHistory paperHistory=new PaperHistory();
        paperHistory.setId(Integer.valueOf(Data.get("historyId")));
        paperHistory.setUserId(Integer.valueOf(Data.get("userId")));
        paperHistory.setPaperId(Integer.valueOf(Data.get("paperId")));
        paperHistory.setAnswer(Data.get("answer"));
        paperHistoryService.update(paperHistory);
        return ResponseEntity.ok(Data);
    }

    @PostMapping("JudgePaper")
    public ResponseEntity<Map> judgePaper (@RequestBody Map<String,String> Data){
        Map<String ,String[]> outPaper=new HashMap<>();

        Integer paperId= Integer.valueOf(Data.get("paperId"));
        JSONArray uPaperAnswer= JSON.parseArray(Data.get("answer"));
        Paper paper=paperService.queryById(paperId);
        String[] yPaperId=paper.getQuestionId().split(",");
        String[] yPaperType=paper.getQuestionType().split(",");
        String[] yPaperAnswer=new String[yPaperId.length];
        String[] out=new String[yPaperId.length];
        for (int i=0 ; i<yPaperId.length;i++){
            if(yPaperType[i].equals("0")){
                yPaperAnswer[i]=choiceService.queryById(Integer.valueOf(yPaperId[i])).getAnswer();
            }
            if(yPaperType[i].equals("1")){
                yPaperAnswer[i]=judgmentService.queryById(Integer.valueOf(yPaperId[i])).getAnswer();
            }
            if(yPaperType[i].equals("2")){
                yPaperAnswer[i]=blankService.queryById(Integer.valueOf(yPaperId[i])).getAnswer();
            }
            if(yPaperType[i].equals("3")){
                yPaperAnswer[i]=short1Service.queryById(Integer.valueOf(yPaperId[i])).getAnswer();
            }
            out[i]= String.valueOf(uPaperAnswer.get(i).equals(yPaperAnswer[i]));
        }
        outPaper.put("Answer",yPaperAnswer);
        outPaper.put("uAnswerTF",out);

        return ResponseEntity.ok(outPaper);
    }
}